/*River Warren
 *October 10, 2011
 *
 *Updated Oct 14 2011, 12:21, remove itoa, replace with sprintf
 *Castle.cpp
*/

#include "Castle.h"
#include <algorithm>

//default constructor
//for new game sets current room to 0
Castle::Castle()
{
    loadRooms();//load rooms into array
    currentRoom = 0;
}

//constructor for continued game
//sets currentRoom to room specified by parameter
Castle::Castle(string roomID)
{
    loadRooms();//load rooms into array
    try{setCurrentRoom(roomID);}
    catch(string msg){throw msg;}
}

Castle::~Castle(){}

string Castle::getDesc()//get description of room
{
    return rooms[currentRoom].getDesc();
}

//move within castle
//must be contained within try catch block
void Castle::move(int direction)
{

    //direction must >=1 && <= 4
    if(direction >= 1 && direction <= 4)
    {
        //set currentRoom to room specified by direction from previous room
        try{setCurrentRoom(rooms[currentRoom].getLink(direction));}
        catch(string msg){throw msg;}
    }
}
bool Castle::unlockDoor(string keyID)//unlock door with proper key Id else throws exception
{
    try {return rooms[currentRoom].unlockDoor(keyID);}
    catch(string msg){throw msg;}
}


bool Castle::hasDoor(){return rooms[currentRoom].hasDoor();}

string Castle::getKeyCode()//returns key code for opening door
{
    return rooms[currentRoom].getKeyCode();
}

//parses room number from string
void Castle::setCurrentRoom(string newRoom)
{
    string msg = "Not a room ID";
    if(newRoom[0] != 'R') throw msg;
    currentRoom = atoi(newRoom.substr(1,newRoom.length() - 1).c_str());
}

//load rooms from files into array
void Castle::loadRooms()
{
    string str;
    char buffer [33];
    Room r;
    for(int i = 0; i <= 30; ++i)
    {
        std::sprintf(buffer, "%d", i);
        str = 'R';
        str += buffer;
        r.loadRoom(str);
        rooms.push_back(r);
    }
}

Room * Castle::getRoom(string roomID) {
    
    Room * roomPtr;
    
    vector<Room>::iterator roomIT;
    
    roomIT = find(rooms.begin(), rooms.end(), roomID);
    
    roomPtr = &(*roomIT);
    return roomPtr;
}
//saves current state of rooms
//right now saves to working directory
//should have path string as parameter
void Castle::saveRooms()
{
    for(int i = 0; i < 30; ++i)
    {
        rooms[i].saveRoom();
    }
}
